export type HandlerType = (...args: any[]) => any;
export type HandlerSetType = Set<HandlerType>;
export default class Store {
  #handlers: Record<string, HandlerSetType> = {};
  public data: Record<string, any> = {};
  public addHandler(key: string, handler: (state: any) => any, invoke = true) {
    try {
      this.#handlers[key].add(handler);
    } catch (error) {
      this.#handlers[key] = new Set([handler]);
    } finally {
      if (invoke) {
        handler(this.data[key]);
      }
    }
  }
  public removeHandler(key: string, handler: HandlerType) {
    this.#handlers[key].delete(handler);
  }
  public update(key: string, value: any) {
    this.data[key] = value;
    const handlers: HandlerSetType = this.#handlers[key];
    if (handlers?.size) {
      handlers.forEach((handler) => handler(value));
    }
  }
}
